package com.ruoyi.quartz.task;

import java.io.File;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.order.OrderUtils;
import com.ruoyi.common.utils.poi.ExcelMultipleSheetsUtil;
import com.ruoyi.custom.domain.TCustomInfo;
import com.ruoyi.custom.service.ITCustomInfoService;
import com.ruoyi.statistic.domain.*;
import com.ruoyi.statistic.service.IWDayReportStatService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.time.*;

/**
 * 定时任务调度，宏林昇库日报表
 * 
 * @author wzy
 */
@Component("drTask")
public class DrTask
{
    @Autowired
    private ITCustomInfoService tCustomInfoService;

    @Autowired
    private IWDayReportStatService wDayReportStatService;

    private static Logger logger = LoggerFactory.getLogger(DrTask.class);

    /**
     * 按客户维度，统计日入/出库量，入/出库总量，当前库存量，6:30~6:30，无参
     */

    public void statisticDayReport(String strDayReportDate)
    {
        logger.debug("统计，按客户维度，统计日入/出库量，入/出库总量，当前库存量，开始 ...");
        /**
         * 计算当前日期，前一天日期
         */
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate today = LocalDate.now();
        if(StringUtils.isNotEmpty(strDayReportDate)) {
            today = LocalDate.parse(strDayReportDate, formatter);
        }
        logger.debug("当前日期: " + today);

        LocalDateTime time = LocalDateTime.now();
        logger.debug("当前时间: " + time);
        LocalDateTime today6 = LocalDateTime.of(time.toLocalDate(), LocalTime.of(6, 30, 0));
        logger.debug("当前6点: " + today6 + "，转化：" + DateUtils.toDate(today6));
        LocalDateTime yesterday6 = today6.minusDays(1);
        logger.debug("前天6点: " + yesterday6 + "，转化：" + DateUtils.toDate(yesterday6));

        Date beginDate = DateUtils.toDate(yesterday6);
        Date endDate = DateUtils.toDate(today6);

        //logger.debug(" DateUtils.toDate(yesterday8): " + Date.valueOf(DateUtils.toDate(yesterday8)));

        // 获取前一天的日期
        LocalDate yesterday = today.minusDays(1);
        logger.debug("前一天日期: " + yesterday);

        TCustomInfo custom = new TCustomInfo();
        List<TCustomInfo> customInfoList = tCustomInfoService.selectTCustomInfoList(custom);

        WDayReportStat dayReportStat = new WDayReportStat();
        String filename, downloadPath, customerName, goodsTransferOrignCustomer;
        double weightTotal = 0.0;
        int sn = 0;
        Map<String, Object> sheets = new LinkedHashMap<>();

        for(TCustomInfo customInfo : customInfoList) {
            customerName = customInfo.getCustomerName();
            filename = UUID.randomUUID().toString() + ".xlsx";
            downloadPath = getAbsoluteFileExt(filename);

            dayReportStat.setDownloadUrl(filename);

            // 日报编号
            dayReportStat.setDayReportStatisticNumber(OrderUtils.getOrderNumber("DR", "-"));
            // 日报日期
            dayReportStat.setDayReportDate(DateUtils.toDate(yesterday6));
            // 客户名称
            dayReportStat.setCustomerName(customInfo.getCustomerName());
            // 入库总量
            weightTotal = 0.0; sn = 0;
            List<WEnterWarehouseSheet> enterWarehouseSheetList = wDayReportStatService.selectWEnterWarehouseSheetListExt(customerName, beginDate, endDate, 1000);
            for(WEnterWarehouseSheet enterWarehouseSheet : enterWarehouseSheetList) {
                enterWarehouseSheet.setSerialNumber(++sn);
                weightTotal = weightTotal + enterWarehouseSheet.getWeight();
            }
            sheets.put("总入库", enterWarehouseSheetList);
            weightTotal = Math.round(weightTotal * 1000.0) / 1000.0;
            dayReportStat.setEnterWarehouseWeight(weightTotal);

            // 出库总量
            weightTotal = 0.0; sn = 0;
            List<WExitWarehouseSheet> exitWarehouseSheetList = wDayReportStatService.selectWExitWarehouseSheetListExt(customerName, beginDate, endDate, 1000);
            for(WExitWarehouseSheet exitWarehouseSheet : exitWarehouseSheetList) {
                exitWarehouseSheet.setSerialNumber(++sn);
                weightTotal = weightTotal + exitWarehouseSheet.getWeight();
                if(exitWarehouseSheet.getInventoryStatus().equals("已出库")) {
                    exitWarehouseSheet.setPickUpGoodsStatus("已实提");
                } else if(exitWarehouseSheet.getInventoryStatus().equals("已在库")) {
                    exitWarehouseSheet.setPickUpGoodsStatus("已货转");
                }
                if(exitWarehouseSheet.getGoodsTransferTimes() < 1) {
                    exitWarehouseSheet.setExitWarehouseMode("正常入库");
                } else {
                    goodsTransferOrignCustomer = getGoodsTransferOrignCustomer(customerName, exitWarehouseSheet.getGoodsTransferIds(), exitWarehouseSheet.getGoodsId());
                    if(StringUtils.isEmpty(goodsTransferOrignCustomer)) {
                        exitWarehouseSheet.setExitWarehouseMode("正常入库");
                    } else {
                        exitWarehouseSheet.setExitWarehouseMode("货转入库");
                        exitWarehouseSheet.setOriginGoodsRightCustomer(goodsTransferOrignCustomer);
                    }
                }
            }
            sheets.put("总出库", exitWarehouseSheetList);
            weightTotal = Math.round(weightTotal * 1000.0) / 1000.0;
            dayReportStat.setExitWarehouseWeight(weightTotal);

            // 货转入库量
            weightTotal = 0.0;
            List<WTransferEnterSheet> transferEnterSheetLiat = wDayReportStatService.selectWTransferEnterSheetListExt(customerName, beginDate, endDate, 1000);
            for(WTransferEnterSheet transferEnterSheet : transferEnterSheetLiat) {
                weightTotal = weightTotal + transferEnterSheet.getWeight();
            }
            sheets.put("转入", transferEnterSheetLiat);
            weightTotal = Math.round(weightTotal * 1000.0) / 1000.0;
            dayReportStat.setTransferEnterWarehouseWeight(weightTotal);

            // 货转出库量
            weightTotal = 0.0;
            List<WTransferExitSheet> transferExitSheetList = wDayReportStatService.selectWTransferExitSheetListExt(customerName, beginDate, endDate, 1000);
            for(WTransferExitSheet transferExitSheet : transferExitSheetList) {
                weightTotal = weightTotal + transferExitSheet.getWeight();
            }
            sheets.put("转出", transferExitSheetList);
            weightTotal = Math.round(weightTotal * 1000.0) / 1000.0;
            dayReportStat.setTransferExitWarehouseWeight(weightTotal);

            // 当前库存量
            weightTotal = 0.0;
            List<WCurrentWarehouseSheet> currentWarehouseSheetList = wDayReportStatService.selectWCurrentWarehouseSheetListExt(customerName, beginDate, endDate, 1000);
            for(WCurrentWarehouseSheet currentWarehouseSheet : currentWarehouseSheetList) {
                weightTotal = weightTotal + currentWarehouseSheet.getWeight();
            }
            sheets.put("库存", currentWarehouseSheetList);
            weightTotal = Math.round(weightTotal * 1000.0) / 1000.0;
            dayReportStat.setCurrentWarehouseWeight(weightTotal);

            // 日入库量
            weightTotal = 0.0; sn = 0;
            List<WDayEnterWarehouseSheet> dayEnterWarehouseSheetList = wDayReportStatService.selectWDayEnterWarehouseSheetListExt(customerName, beginDate, endDate, 1000);
            for(WDayEnterWarehouseSheet dayEnterWarehouseSheet : dayEnterWarehouseSheetList) {
                dayEnterWarehouseSheet.setSerialNumber(++sn);
                weightTotal = weightTotal + dayEnterWarehouseSheet.getWeight();
            }
            sheets.put("当日入库", dayEnterWarehouseSheetList);
            weightTotal = Math.round(weightTotal * 1000.0) / 1000.0;
            dayReportStat.setDayEnterWarehouseWeight(weightTotal);

            // 日出库量
            weightTotal = 0.0; sn = 0;
            List<WDayExitWarehouseSheet> dayExitWarehouseSheetList = wDayReportStatService.selectWDayExitWarehouseSheetListExt(customerName, beginDate, endDate, 1000);
            for(WDayExitWarehouseSheet dayExitWarehouseSheet : dayExitWarehouseSheetList) {
                dayExitWarehouseSheet.setSerialNumber(++sn);
                weightTotal = weightTotal + dayExitWarehouseSheet.getWeight();
                if(dayExitWarehouseSheet.getInventoryStatus().equals("已出库")) {
                    dayExitWarehouseSheet.setPickUpGoodsStatus("已实提");
                } else if(dayExitWarehouseSheet.getInventoryStatus().equals("已在库")) {
                    dayExitWarehouseSheet.setPickUpGoodsStatus("已货转");
                }
                if(dayExitWarehouseSheet.getGoodsTransferTimes() < 1) {
                    dayExitWarehouseSheet.setExitWarehouseMode("正常入库");
                } else {
                    goodsTransferOrignCustomer = getGoodsTransferOrignCustomer(customerName, dayExitWarehouseSheet.getGoodsTransferIds(), dayExitWarehouseSheet.getGoodsId());
                    if(StringUtils.isEmpty(goodsTransferOrignCustomer)) {
                        dayExitWarehouseSheet.setExitWarehouseMode("正常入库");
                    } else {
                        dayExitWarehouseSheet.setExitWarehouseMode("货转入库");
                        dayExitWarehouseSheet.setOriginGoodsRightCustomer(goodsTransferOrignCustomer);
                    }                }
            }
            sheets.put("当日出库", dayExitWarehouseSheetList);
            weightTotal = Math.round(weightTotal * 1000.0) / 1000.0;
            dayReportStat.setDayExitWarehouseWeight(weightTotal);

            // 写入xlsx
            ExcelMultipleSheetsUtil.excelMultipleSheets(sheets, "", "", downloadPath);

            dayReportStat.setCreateBy("DrTask");
            if(wDayReportStatService.insertWDayReportStat(dayReportStat) < 1)
            {
                logger.error("统计失败: " + customInfo.getCustomerName() + "，统计时间：" + yesterday);
            }
        }
        logger.debug("统计，按客户维度，统计日入/出库量，入/出库总量，当前库存量，结束 ...");
    }

    /**
     * 获取下载路径
     *
     * @param filename 文件名称
     */
    private String getAbsoluteFileExt(String filename)
    {
        String downloadPath = RuoYiConfig.getDownloadPath() + filename;
        File desc = new File(downloadPath);
        if (!desc.getParentFile().exists())
        {
            desc.getParentFile().mkdirs();
        }
        return downloadPath;
    }

    /**
     * 获取转入货主
     *
     * @param customerName 客户名称
     * @param goodsTransferIds 货转IDs
     * @param goodsId 货物ID
     */
    private String getGoodsTransferOrignCustomer(String customerName, String goodsTransferIds, long goodsId)
    {
        logger.debug("QQQ getGoodsTransferOrignCustomer goodsTransferIds： " + goodsTransferIds);
        String[] transferIds = goodsTransferIds.split(",");
        return wDayReportStatService.selectGoodsTransferOrignCustomerExt(customerName, transferIds, goodsId);
    }

}
